package com.example.bbs.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.bbs.R;
import com.example.bbs.base.Data;
import com.example.bbs.bean.LoginData;
import com.example.bbs.bean.User;
import com.example.bbs.config.HttpConstant;
import com.example.bbs.util.HttpUtil;

import java.util.concurrent.CompletableFuture;


public class MyLoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String LOG_TAG = MyLoginActivity.class.getSimpleName();
    private EditText etLoginActivityUsername;
    private EditText etLoginActivityPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mylogin);

        initView();
    }

    private void initView() {
        // 初始化控件
        Button btnLoginActivityLogin = findViewById(R.id.btn_confirm);
        etLoginActivityUsername = findViewById(R.id.et_username);
        etLoginActivityPassword = findViewById(R.id.et_password);

        // 设置点击事件监听器
        btnLoginActivityLogin.setOnClickListener(this);
    }

    public void onClick(View view) {
        /*
         * 登录验证：
         *
         *  从EditText的对象上获取文本编辑框输入的数据，并把左右两边的空格去掉
         *  String name = mEtLoginactivityUsername.getText().toString().trim();
         *  String password = mEtLoginactivityPassword.getText().toString().trim();
         *  进行匹配验证,先判断一下用户名密码是否为空，
         *  if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password))
         *  再进而for循环判断是否与数据库中的数据相匹配
         *  if (name.equals(user.getName()) && password.equals(user.getPassword()))
         *  一旦匹配，立即将match = true；break；
         *  否则 一直匹配到结束 match = false；
         *
         *  登录成功之后，进行页面跳转：
         *
         *  Intent intent = new Intent(this, MainActivity.class);
         *  startActivity(intent);
         *  finish();//销毁此Activity
         */
        if (view.getId() == R.id.btn_confirm) {
            String name = etLoginActivityUsername.getText().toString().trim();
            String password = etLoginActivityPassword.getText().toString().trim();
            String email = "";
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(password)) {

                CompletableFuture.runAsync(() -> {
                    JSONObject response = HttpUtil.post(HttpConstant.REQUEST_LOGIN,
                            JSON.toJSONString(new LoginData(name, password, email)));
                    runOnUiThread(() -> {
                        if (response != null && response.getBoolean(HttpConstant.FIELD_REPLY)) {
                            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();

                            Data.myself = response.getObject(HttpConstant.FIELD_DATA, User.class);
                            if (Data.myself == null) {
                                Log.d(LOG_TAG, "mm:" + response.getJSONObject(HttpConstant.FIELD_DATA).toString());
                            }
                            Data.myself.setName(name);
                            Data.myself.setPassword(password);
                            Log.d(LOG_TAG, "myself: " + JSON.toJSONString(Data.myself));
                            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                                    .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

                            Intent intent = new Intent(this, MainActivity.class);
                            startActivity(intent);
                            finish();//销毁此Activity
                        } else {
                            Toast.makeText(this, "用户名或密码不正确，请重新输入", Toast.LENGTH_SHORT).show();
                        }
                    });
                });
            } else {
                Toast.makeText(this, "请输入你的用户名或密码", Toast.LENGTH_SHORT).show();
            }
        }
    }
}